package com.kyb.cms.util;

import lombok.extern.slf4j.Slf4j;
import org.armada.galileo.common.util.JsonUtil;
import org.armada.galileo.exception.BizException;
import org.armada.galileo.mvc_plus.encrypt.EncryptUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginCookieUtil {

    public static void main(String[] args) {
        String cokie = "CYVwzE6wpYtDtdemf4TfO3nXyBu4EuRP/TiNWU9wY8AM4ysezpYCugmzWmWYjWWjPytDqMWwz1W8CrPW4rAIYbvFSQIFuG/sKFJXOPhfPabhnQWF08d7RwKtXX1vmGbP0WIbIEl9DRrNDeYX11rpQ2nTzYfHKseNGta/OyGniS7ski3ndnP3u6WWEgpj1P2WL24bBTOWIH0/dF5Tsu5EhRsDV6i7mQNn/AzD4qEwFFDLRLzBzKqse6NOFHgHbYJHXIF9nA2GRGsGjE0YULK9RS1lAw3gFtjCuBI8ApW9ldTRgO5q6CmDxxccXxdu7pu5e3MOZ0WVH6NysfNtHD85m4mb+kyWKIp8k5OYYeDi8akTcMyS5I1WFqG63ScYU+OQ9oY8yqLPSDvfQWqjPVH5EggSG6jdGmO76iBlikn8k0e70LbPondCfpY2d6dnmvPW+K9iN92z0gugYbSJ8NbKULDWgQz8JAnETS0aVqQOPERey8sy7cYrmmhy2znLju3VzHM73ep/3W+cE1C4AHR4PS1lAw3gFtjCuBI8ApW9ldS6Ddts3XGe16K4m5W6wNwn8qpS/0pVIOvNT1q2BJW+eMzkXhSctksgBiM7ADG/bdVRadbha5CwGcGwTAXi8oXhFhSMaxm8po3Excru8OdPmTRQBiCNlaRzxw4JOwLfCRmE+ZqR9hZCPbOvR1x0WauK3VlQNNvF/gyVDXkkRSNcAaTLC4cPe6Desle0PzJ+gcU=";

        String v = EncryptUtil.aesDecodeBase64(cokie, GlobalConstant.KEY);

        System.out.println(v);
    }

    public static void setCookie(String cookieKey, String cookieValue, HttpServletResponse response) {
        if (GlobalConstant.Agent_User_Login_Cookie_Head.equals(cookieKey)) {
            throw new BizException("该 cookie不能使用");
        }
        try {
            String encode = EncryptUtil.aesEncodeBase64(cookieValue, GlobalConstant.KEY);
            Cookie cookie = new Cookie(cookieKey, encode);
            cookie.setMaxAge(24 * 60 * 60);
            cookie.setPath("/");
            cookie.setHttpOnly(true);

            response.addCookie(cookie);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }


    public static void setCookieWithoutEncrypt(String cookieKey, String cookieValue, HttpServletResponse response) {
        if (GlobalConstant.Agent_User_Login_Cookie_Head.equals(cookieKey)) {
            throw new BizException("该 cookie不能使用");
        }
        try {
            Cookie cookie = new Cookie(cookieKey, cookieValue);
            cookie.setMaxAge(24 * 180 * 60 * 60);
            cookie.setPath("/");
            cookie.setHttpOnly(true);

            response.addCookie(cookie);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }


    public static String getCookie(String cookieKey, HttpServletRequest request) {

        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieKey)) {
                String v = cookie.getValue();
                try {
                    v = EncryptUtil.aesDecodeBase64(v, GlobalConstant.KEY);
                } catch (Exception e) {
                }
                return v;
            }
        }
        return null;
    }

    public static void clearCookie(String cookieKey, HttpServletResponse response) {
        String cookieValue = "";
        Cookie cookie = new Cookie(cookieKey, cookieValue);

        cookie.setMaxAge(0);

        cookie.setPath("/");
        cookie.setHttpOnly(true);

        response.addCookie(cookie);
    }


    public static void clearLogin(HttpServletResponse response) {

        clearCookie(GlobalConstant.Agent_User_Login_Cookie_Head, response);

        clearCookie(GlobalConstant.Agent_User_Login_Cookie_Head, response);

    }


    public static void setLoginData(LoginUser u, HttpServletResponse response) {
        if (u == null) {
            throw new BizException("user is null");
        }
        try {
            String cookieValue = JsonUtil.toJson(u);
            String encode = EncryptUtil.aesEncodeBase64(cookieValue, GlobalConstant.KEY);
            Cookie cookie = new Cookie(GlobalConstant.Agent_User_Login_Cookie_Head, encode);
            cookie.setMaxAge(24 * 60 * 60);
            cookie.setPath("/");
            cookie.setHttpOnly(true);

            response.addCookie(cookie);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 将二进制转换成16进制字符串
     *
     * @param buf
     * @return
     */
    public static String byte2Hex(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * java将16进制字符串转换为二进制数组
     *
     * @param hexStr
     * @return
     */
    public static byte[] hex2Byte(String hexStr) {
        if (hexStr.length() < 1) return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }


    public static LoginUser getUserByCookie(String cookieHead, HttpServletRequest request) {
        String v = LoginCookieUtil.getCookie(cookieHead, request);
        LoginUser loginUser = null;
        if (v != null) {
            try {
                loginUser = JsonUtil.fromJson(v, LoginUser.class);
                ThreadUser.set(loginUser);
            } catch (Exception e) {
            }
        }
        return loginUser;
    }

}
